<?php
/**
 *
 * @author 天意
 * @version 1.0
 */
class Router
{
	private $_model = 0;
	private $_uri = array();
	private $_config = array();
    public function __construct($config)
    {
		$this->_config = $config;
		if(isset($this->_config['SERVER_MODE'])){
			$this->_model = $this->_config['SERVER_MODE'];
		}
		$this->_uri = $this->getUriArray();
		if(empty($this->_config['rules'])){
			$this->runrouter(); //路由处理器
		}else{
			$this->run_Rules(); //路由规则
		}
		if(!empty($this->_config['Html_Suffix'])){
			$this->run_Html_Suffix(); //路由后缀
		}
    }
	private function getUriArray(){
		if($this->_model){
			$model = strtolower($this->_model);
			if($model =='iis') $uri = $_SERVER['ORIG_PATH_INFO'];
			else if($model =='nginx') $uri = $_SERVER['PHP_SELF'];
			else if($model =='kangle') $uri = $_SERVER['PHP_SELF'];
			else if($model =='apache') $uri = $_SERVER['DOCUMENT_URI'];
			else if($model =='php-fpm') $uri = $_SERVER['PHP_SELF'];
		}
		else{
			$uri = isset($_SERVER['DOCUMENT_URI']) ? $_SERVER['DOCUMENT_URI'] : (isset($_SERVER['ORIG_PATH_INFO']) ? $_SERVER['ORIG_PATH_INFO'] :$_SERVER['PHP_SELF']);//测试
		}
		//print_r($_SERVER['REQUEST_URI']);
		//$uri = $_SERVER['ORIG_PATH_INFO']; //iis
        $uri_arr = explode("/", trim($uri, '/'));
        $web_root_str = strtr($_SERVER['SCRIPT_FILENAME'], '/', '\\');
        $root_path_arr = explode('\\', trim($web_root_str, '\\'));
        $root_path_count = count($root_path_arr);
        $uri_arr_start = 0;
        foreach($uri_arr as $key => $val)
        {

            if ($val == $root_path_arr[$root_path_count-1])
            {
                $uri_arr_start = $key;
            }
        }
        if ($uri_arr_start >= 0)
        {
            $uri_new = array_slice($uri_arr, $uri_arr_start + 1);
        }
        else
        {
            $uri_new = $uri_arr;
        }
		//print_r($_SERVER); //用于测试
		return $uri_new;
	}
    private function runrouter()
    {
		$uri_new = $this->_uri;
        $uri['c'] = isset($_GET['c'])?$_GET['c']:(isset($uri_new['0'])?(!empty($uri_new['0'])?$uri_new['0']:"index"):"index");
        $uri['a'] = isset($_GET['a'])?$_GET['a']:(isset($uri_new['1'])?(!empty($uri_new['1'])?$uri_new['1']:"index"):"index");

        if (count($uri_new) > 2)
        {
            $uri['uri'] = array_slice($uri_new, 1);
        }
		$this->_uri = $uri;
    }
	public function getRouter(){
		return $this->_uri;
	}
	private function run_Html_Suffix(){
		$Html_Suffix = '.'.$this->_config['Html_Suffix'];
		if(isset($this->_uri['uri']) && !empty($this->_uri['uri'])){
			$endParam = end($this->_uri['uri']);
			if($endParam === $Html_Suffix)  throw new RouterException('404 Found File');
			$htmlfind = stripos($endParam,$Html_Suffix);
			$len = count($this->_uri['uri'])-1;
			$serverpath = parse_url($_SERVER['REQUEST_URI']);
			$serverpath = $serverpath['path'];
			$uripath = parse_url($this->_uri['uri'][$len]);
			$uripath = $uripath['path'];
			$_lensuffix = -strlen($Html_Suffix);
			$serversuffix =  strtolower(substr($serverpath,$_lensuffix));
			$suffix = strtolower(substr($uripath,$_lensuffix));
			/*
				1.找html后缀
				2.html后缀不后带有/
				3.同2一起使用
			*/
			if($htmlfind === false || strcasecmp($suffix,$Html_Suffix) !== 0 || strcasecmp($serversuffix,$suffix) !== 0){
				throw new RouterException('404 Found'); //放弃,观察
			}else{
				$this->_uri['uri'][$len] = substr($endParam,0,$htmlfind);
			}
		}else{
			$htmlfind = stripos($this->_uri['a'],$Html_Suffix);
			if($htmlfind !== false) $this->_uri['a'] = substr($this->_uri['a'],0,$htmlfind);
		}
	}
	private function run_Rules(){
		$rules = $this->_config['rules'];
			$uri = $this->_uri;
			$uri_new = implode('/',$uri);
			$params = array();
			$suffix = '.'.$this->_config['Html_Suffix'];
			foreach($rules as $rule => $_action){
				$finds = stripos($rule,':');
				$_params = $_paramsvalue = array();
				$t = $tt = $u = '';
				/*找不到 $u重新截取*/
				if(false === $finds){
					if(!empty($this->_config['Html_Suffix']))
						$u = substr($uri_new,0,-strlen($suffix));
					else
						$u = $uri_new;
				/*找到 $u $t $tt $_params $_paramsvalue 取值*/
				}else{
				    $u = substr($uri_new,0,$finds);
					$t = substr($uri_new,$finds);
					$tt = substr($rule,$finds);
					$_params = explode('/',$tt);
					$_paramsvalue = explode('/',$t);
				}
				/* if 匹配带有参数的 && 匹配规则 && 参数和值要对应*/
				if($finds !== false && strcasecmp($u , substr($rule,0,$finds)) === 0 && count($_params) === count($_paramsvalue) ){
					list($action['c'],$action['a']) = explode('/',$_action);
					foreach($_params as $k =>$v){
						if($v{0} == ':'){
							$params[] = substr($v,1);
							$params[] = $_paramsvalue[$k];
						}
					}
					break;
				/*elseif 匹配不带有参数的 && 参数和值等于零 */
				}elseif(strcasecmp($u,$rule) === 0 && count($_params) ==0){
					list($action['c'],$action['a']) = explode('/',$_action);
					break;
				}
			}

			if(empty($action)){
				throw new RouterException('403 Found'); //放弃,观察
			}else{
				if(empty($params)){
					array_unshift($params,$uri_new);
				}else{
					array_unshift($params,$action['a']);
				}
				$action['uri'] = $params;
				$this->_uri = $action;
			}

	}
	public function redirct($action = '',$local = false){
		if(!empty($action)){
			if($local)
				header("location:{$action}");
		}else{
			throw new RouterException('parse router is error');
		}
	}
}

class RouterException extends DingException{
}